using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour
{

    public float walkSpeed = 4.0F;                  // velocidad para andar
     public float runSpeed = 9.0F;                   // velocidad para correr
    //    public float jumpSpeed = 8.0F;                  // velocidad necesaria para saltar
    public float gravity = 20.0F;                   // velocidad de caida tras saltar
    public float rotationSpeed = 0.1f;              // velocidad de rotacion
    [HideInInspector]
    public bool enEscalera = false;

    private CharacterController controller;
    private Vector3 moveDirection = Vector3.zero;
    private Vector3 rotateDirection = Vector3.zero;

    public float actionCheckTime = 1.0f;            // tiempo de espera entre acciones. para controlar mantener pulsado boton de accion
    private float time;                             // tiempo del juego
    private bool actionInUse = false;               // variable para controlar si se esta realizando alguna accion 
    [HideInInspector]
    public GameObject objectWitAction;              // gameobject que recive la accion activa
    [HideInInspector]
    public ActionConstants.Action accion;
    [HideInInspector]
    public ActionsControl actionsControl;

    void Start()
    {
        actionsControl = new ActionsControl();
        time = Time.timeSinceLevelLoad;
    }

    void Update()
    {
        controller = GetComponent<CharacterController>();
        #region	Input TECLADO
        // MOVIMIENTOS
        // teclas de adelante y atras
        if (Input.GetKey(InputConstants.KEY_UP))
        {
            if (enEscalera)
                moveDirection.y = 1;
            else
                moveDirection.z = 1;
        }
        else if (Input.GetKey(InputConstants.KEY_DOWN))
        {
            if (enEscalera)
                moveDirection.y = -1;
            else
                moveDirection.z = -1;
        }
        else
        {
            moveDirection.y = 0;
            moveDirection.z = 0;
        }
        
        // teclas de derecha e izquierda
        if (Input.GetKey(InputConstants.KEY_RIGHT))
        {
            if (!enEscalera)
                moveDirection.x = 1;
        }
        else if (Input.GetKey(InputConstants.KEY_LEFT))
        {
            if (!enEscalera)
                moveDirection.x = -1;
        }
        else
            moveDirection.x = 0;

        // GIROS 
        // teclas de adelante y atras
        if (Input.GetKey(InputConstants.KEY_ARROW_UP))
            rotateDirection.z = 1;
        else if (Input.GetKey(InputConstants.KEY_ARROW_DOWN))
            rotateDirection.z = -1;
        else
            rotateDirection.z = 0;

        // teclas de derecha e izquierda
        if (Input.GetKey(InputConstants.KEY_ARROW_RIGHT))
            rotateDirection.x = 1;
        else if (Input.GetKey(InputConstants.KEY_ARROW_LEFT))
            rotateDirection.x = -1;
        else
            rotateDirection.x = 0;

        if (this.moveDirection != Vector3.zero)
        {
            if (controller.isGrounded || enEscalera)
            {
                // teclas de correr
                if (Input.GetKey(InputConstants.KEY_RUN) || Input.GetKey(InputConstants.KEY_RUN_2))
                {
                    // if correr activado   descomentar runSpeed
                    moveDirection *= runSpeed;
                    controller.Move(moveDirection * Time.deltaTime);
                }
                else
                {
                    moveDirection *= walkSpeed;
                    controller.Move(moveDirection * Time.deltaTime);
                }
            }
            else
            {
                // aplica efecto de gravedad
                if (!enEscalera)
                {
                    moveDirection.y -= gravity;
                    controller.Move(moveDirection * Time.deltaTime);
                }
            }
            // Rotacion para encarar la direccion de movimiento
            // transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), rotationSpeed * Time.deltaTime);
            // aplicamos movimiento
            
        }
        else
        {
            // si no hay movimiento, solo se aplica efecto de gravedad
            if (!enEscalera)
            {
                moveDirection.y -= gravity;
                controller.Move(moveDirection * Time.deltaTime);
            }
        }

        if (this.rotateDirection != Vector3.zero)
        {
            // Rotacion para encarar la direccion de movimiento
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(rotateDirection), rotationSpeed * Time.deltaTime);
        }


        // comprobar si se ha pulsado teclas de accion
        // aqui se podrian hacer acciones en movimiento. si se requiere estar parado, ponerlo en el else de arriba
        if (Input.GetKey(InputConstants.KEY_ACTION))
        {
            if (objectWitAction != null)        // si estamos dentro de algun trigger-hud cuando pulsamos 
            {
                if ((time + actionCheckTime) < Time.timeSinceLevelLoad)
                {
                    time = Time.timeSinceLevelLoad;
                    actionInUse = actionsControl.StartAction(accion);         // iniciamos la accion
                }

            }
        }
        #endregion

        #region PAD
        moveDirection = Vector3.zero;



        if (Input.GetButtonDown("PadVertical"))
            moveDirection.z = 1;
        else if (Input.GetKey(InputConstants.KEY_DOWN))
            moveDirection.z = -1;
        else
            moveDirection.z = 0;

        // teclas de derecha e izquierda
        if (Input.GetKey(InputConstants.KEY_RIGHT))
            moveDirection.x = 1;
        else if (Input.GetKey(InputConstants.KEY_LEFT))
            moveDirection.x = -1;
        else
            moveDirection.x = 0;

        moveDirection = new Vector3(Input.GetAxis("PadHorizontal"), 0, Input.GetAxis("PadVertical"));

        // GIROS 
        // teclas de adelante y atras
        if (Input.GetKey(InputConstants.KEY_ARROW_UP))
            rotateDirection.z = 1;
        else if (Input.GetKey(InputConstants.KEY_ARROW_DOWN))
            rotateDirection.z = -1;
        else
            rotateDirection.z = 0;

        // teclas de derecha e izquierda
        if (Input.GetKey(InputConstants.KEY_ARROW_RIGHT))
            rotateDirection.x = 1;
        else if (Input.GetKey(InputConstants.KEY_ARROW_LEFT))
            rotateDirection.x = -1;
        else
            rotateDirection.x = 0;

        if (this.moveDirection != Vector3.zero)
        {
            // teclas de correr
            if (Input.GetKey(InputConstants.KEY_RUN) || Input.GetKey(InputConstants.KEY_RUN_2))
            {
                // if correr activado   descomentar runSpeed
                //moveDirection *= runSpeed;
                controller.Move(moveDirection * Time.deltaTime);
            }
            else
            {
                Debug.Log("------");
                moveDirection *= walkSpeed;
                controller.Move(moveDirection * Time.deltaTime);
            }

            // Rotacion para encarar la direccion de movimiento
            // transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), rotationSpeed * Time.deltaTime);
        }
        else
        {
            // si no se mueve, a direccion Zero
            //  controller.Move(moveDirection);             // no funciona para las colisiones
        }

        if (this.rotateDirection != Vector3.zero)
        {
            // Rotacion para encarar la direccion de movimiento
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(rotateDirection), rotationSpeed * Time.deltaTime);
        }


        // comprobar si se ha pulsado teclas de accion
        // aqui se podrian hacer acciones en movimiento. si se requiere estar parado, ponerlo en el else de arriba
        if (Input.GetKey(InputConstants.KEY_ACTION))
        {
            if (objectWitAction != null)        // si estamos dentro de algun trigger-hud cuando pulsamos 
            {
                if ((time + actionCheckTime) < Time.timeSinceLevelLoad)
                {
                    time = Time.timeSinceLevelLoad;
                    actionInUse = actionsControl.StartAction(accion);         // iniciamos la accion
                }

            }
        }
        #endregion

        // si hay accion en activo
        if (actionInUse)
        {
            actionsControl.doAction(this, objectWitAction);
        }

    }

    public void EntraEscalera(GameObject pos)
    {
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(pos.transform.forward), rotationSpeed);   
        enEscalera = true;
        this.transform.Translate(pos.transform.position.x - this.transform.position.x, 0, pos.transform.position.z - this.transform.position.z);
    }

    public void SaleEscalera()
    {
        if (enEscalera)
            enEscalera = false;
    }

    public void setObjectWithAction(GameObject GO, ActionConstants.Action accion)
    {
        this.objectWitAction = GO;
        this.accion = accion;
    }

    public void clearObjectWitAction()
    {
        actionInUse = false;
        this.objectWitAction = null;
        this.accion = ActionConstants.Action.NONE;
        actionsControl.finishAction();
    }

    void OnTriggerEnter(Collider hit)
    {
        if (hit.gameObject.name == StringConstants.TRIGGER_ABAJO)
        {
            if (enEscalera)
            {
                enEscalera = false;
            }
        }
        if (hit.gameObject.name == StringConstants.TRIGGER_ARRIBA)
        {
            if (enEscalera)
            {
                enEscalera = false;
            }
        }
    }

    void OnTriggerStay(Collider hit)
    {
        if (hit.gameObject.name == StringConstants.TRIGGER_ABAJO)
        {
            
        }
        if (hit.gameObject.name == StringConstants.TRIGGER_ARRIBA)
        {
            
        }
    }

}